package com.parking.renters.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.parking.common.core.model.PageInfo;
import com.parking.common.core.model.Result;
import com.parking.common.core.model.StateData;
import com.parking.common.core.util.CardIdUtil;
import com.parking.common.web.util.OssUtil;
import com.parking.renters.dao.RentersMapper;
import com.parking.renters.entity.Renters;
import com.parking.renters.entity.RentersInfo;
import com.parking.renters.dao.RentersInfoMapper;
import com.parking.renters.exception.RentersException;
import com.parking.renters.exceptionCode.RentersExceptionCode;
import com.parking.renters.form.CertifiedDto;
import com.parking.renters.inter.CertifiedClient;
import com.parking.renters.model.stallCall.dto.RentersDtos;
import com.parking.renters.model.stallCall.dto.RentersInfoDto;
import com.parking.renters.model.stallCall.dto.SelectRentersInfoByIdDTO;
import com.parking.renters.model.stallCall.form.AuthenticationNameForm;
import com.parking.renters.model.stallCall.form.PerfectCertifiedForm;
import com.parking.renters.model.stallCall.form.SelectRentersForm;
import com.parking.renters.model.stallCall.form.UpdateRentersImgForm;
import com.parking.renters.service.RentersInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 彭于晏
 * @since 2023年11月29日
 */
@Service
public class RentersInfoServiceImpl extends ServiceImpl<RentersInfoMapper, RentersInfo> implements RentersInfoService {
    @Resource
    private RentersInfoMapper rentersInfoMapper;
    @Resource
    private RentersMapper rentersMapper;
    @Resource
    private OssUtil ossUtil;
    @Resource
    private CertifiedClient certifiedClient;

    /***
     *根据id查询出租客信息
     * @param rentersInfoId
     * @return
     */
    @Override
    public RentersInfoDto selectRentersInfoById(Integer rentersInfoId) {
        QueryWrapper<RentersInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("renters_info_id",rentersInfoId);
        RentersInfo info = rentersInfoMapper.selectOne(wrapper);
        if (info==null){
            throw new RentersException(RentersExceptionCode.RENTERS_INFO_NOT_EXISTS);
        }
        if (info.getRentersRealNameState()!= StateData.RENTERS_REAL_NAME_STATE_YES){
            throw new RentersException(RentersExceptionCode.RENTERS_REAL_NAME_NO);
        }
        RentersInfoDto dto = BeanUtil.toBean(info, RentersInfoDto.class);
        return dto;
    }

    /***
     * 出租客实名认证
     * @param form 出租客实名认证需要的参数
     */
    @Override
    public Boolean AuthenticationName(AuthenticationNameForm form,Integer rentersId) throws IOException {
        Renters account = rentersMapper.selectById(rentersId);
        if (account==null) {
            throw new RentersException(RentersExceptionCode.RENTERS_NOT_EXISTS);
        }
        if (account.getRentersState()!= StateData.RENDERS_STATE_ENABLE) {
            throw new RentersException(RentersExceptionCode.RENTERS_STATE_IS_NOT_ENABLE);
        }
        QueryWrapper<RentersInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("renters_id",rentersId);
        RentersInfo rentersInfo = rentersInfoMapper.selectOne(wrapper);
        rentersInfo.setRentersInfoCard(form.getRentersInfoCard());
        rentersInfo.setRentersInfoName(form.getRentersInfoName());
        rentersInfo.setRentersRealNameState(StateData.RENTERS_REAL_NAME_STATE_YES);
        rentersInfo.setRentersInfoAge(this.getAgeFromIdCard(form.getRentersInfoCard()));
        rentersInfoMapper.updateById(rentersInfo);
        return CardIdUtil.checkIdCard(form.getRentersInfoCard(), form.getRentersInfoName());
    }

    /***
     * 查询出租客是否实名认证
     * @param rentersInfoId
     * @return
     */
    @Override
    public RentersInfoDto selectRentersRealName(Integer rentersInfoId) {
        RentersInfo rentersInfo = rentersInfoMapper.selectById(rentersInfoId);
        Renters renters = rentersMapper.selectById(rentersInfo.getRentersId());
        if (renters==null) {
            throw new RentersException(RentersExceptionCode.RENTERS_NOT_EXISTS);
        }
        if (renters.getRentersState()!= StateData.RENDERS_STATE_ENABLE) {
            throw new RentersException(RentersExceptionCode.RENTERS_STATE_IS_NOT_ENABLE);
        }
        if (rentersInfo.getRentersRealNameState()== StateData.RENTERS_REAL_NAME_STATE_NO) {
            throw new RentersException(RentersExceptionCode.RENTERS_REAL_NAME_NO);
        }
        RentersInfoDto dto = BeanUtil.toBean(rentersInfo, RentersInfoDto.class);
        return dto;
    }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /**
     * 从身份证获取年龄
     * */
    public  int getAgeFromIdCard(String idCard) {
        int age = 0;
        if (idCard.length() == 18) {
            int birthYear = Integer.parseInt(idCard.substring(6, 10));
            int currentYear = Calendar.getInstance().get(Calendar.YEAR);
            age = currentYear - birthYear;
        }
        return age;
    }
    /***
     *
     * 平台按条件查询出租客
     * @param form
     * @return
     */
    @Override
    public PageInfo selectRentersInfo(SelectRentersForm form) {
        Page<RentersInfo> page = new Page<>(form.getPageNum()!=null?form.getPageNum():1, form.getPageSize()!=null?form.getPageSize():4);
        QueryWrapper<RentersInfo> wrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotEmpty(form.getCondition())) {
            wrapper.like("renters_info_name",form.getCondition());
            wrapper.or();
            wrapper.like("renters_info_tel",form.getCondition());
        }
        if (ObjectUtil.isNotEmpty(form.getCondition())) {
            wrapper.like("certified_info_name",form.getCertifiedInfoName());
        }
        rentersInfoMapper.selectPage(page, wrapper).getRecords();
        List<RentersDtos> rentersDtos = BeanUtil.copyToList(page.getRecords(), RentersDtos.class);
        for (RentersDtos rentersDto : rentersDtos) {
            Renters renters = rentersMapper.selectById(rentersDto.getRentersId());
            rentersDto.setRentersAccount(renters.getRentersAccount());
            rentersDto.setRentersState(renters.getRentersState());
        }
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPages(page.getPages());
        pageInfo.setRecords(rentersDtos);
        return pageInfo;
    }

    /***
     * 物业按条件查询出租客
     * @param form
     * @return
     */
    @Override
    public PageInfo selectRenters(SelectRentersForm form) {
        Page<RentersInfo> page = new Page<>(form.getPageNum()==null?form.getPageNum():1, form.getPageSize()!=null?form.getPageSize():4);
        QueryWrapper<RentersInfo> wrapper = new QueryWrapper<>();
        wrapper.select("renters_info_id", "name", "phone")
                .eq("renters_info_id", form.getCondition());
        List<RentersInfo> list = rentersInfoMapper.selectPage(page, wrapper).getRecords();
        System.out.println(list+"999999999959999999531");
        if (list == null || list.isEmpty()) {
            throw new RentersException(RentersExceptionCode.RENTERS_NOT_EXISTS);
        }
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPages(page.getPages());
        pageInfo.setRecords(list);
        return pageInfo;
    }

    /***
     * 修改出租客信息
     * @param rentersInfoId
     * @param rentersInfoTel
     */
    @Override
    public void updateRenters(Integer rentersInfoId, String rentersInfoTel) {
        QueryWrapper<RentersInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("renters_info_id",rentersInfoId);
        RentersInfo rentersInfo = rentersInfoMapper.selectById(wrapper);
        if (rentersInfo==null){
            throw new RentersException(RentersExceptionCode.RENTERS_NOT_EXISTS);
        }
        RentersInfo info = new RentersInfo();
        info.setRentersInfoTel(rentersInfoTel);
        rentersInfoMapper.updateById(info);
    }

    /***
     * (车位模块调用)根据id查询出租客信息
     * @param rentersInfoId
     * @return
     */
    @Override
    public SelectRentersInfoByIdDTO rentersInfoCallById(Integer rentersInfoId) {
        if (rentersInfoId==0){
            throw new RentersException(RentersExceptionCode.RENTERS_INFO_NOT_EXISTS);
        }
        QueryWrapper<RentersInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("renters_info_id",rentersInfoId);
        RentersInfo rentersInfo = rentersInfoMapper.selectOne(wrapper);
        if (rentersInfo==null){
            throw new RentersException(RentersExceptionCode.RENTERS_INFO_NOT_EXISTS);
        }
        SelectRentersInfoByIdDTO dto = BeanUtil.toBean(rentersInfo, SelectRentersInfoByIdDTO.class);
        return dto;
    }

    /***
     * 出租客上传头像
     * @param path
     * @param rentersId
     */
    @Override
    public void upLoad(String path, Integer rentersId) {
        Renters renters = rentersMapper.selectById(rentersId);
        QueryWrapper<RentersInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("renters_id",renters.getRentersId());
        RentersInfo rentersInfo = rentersInfoMapper.selectOne(wrapper);
        if (rentersInfo==null) {
            throw new RentersException(RentersExceptionCode.RENTERS_NOT_EXISTS);
        }
        if (renters.getRentersState()!=StateData.RENDERS_STATE_ENABLE){
            throw new RentersException(RentersExceptionCode.RENTERS_STATE_IS_NOT_ENABLE);
        }
        rentersInfo.setRentersInfoImg(path);
        rentersInfoMapper.updateById(rentersInfo);
    }

    /***
     * 出租客修改头像
     * @param form
     * @throws IOException
     */
    @Override
    public void updateRentersImg(UpdateRentersImgForm form) throws IOException {
        Renters renters = rentersMapper.selectById(form.getRentersInfoId());
        if (renters==null) {
            throw new RentersException(RentersExceptionCode.RENTERS_INFO_NOT_EXISTS);
        }
        if (renters.getRentersState()!= StateData.RENDERS_STATE_ENABLE) {
            throw new RentersException(RentersExceptionCode.RENTERS_STATE_IS_NOT_ENABLE);
        }
        RentersInfo rentersInfo = rentersInfoMapper.selectById(form.getRentersInfoId());
        //上传返回的新地址
        String newPath = ossUtil.uploadFile(form.getImage().getInputStream(), form.getFileName());
        //获取旧的头像地址
        String path = FileNameUtil.getName(rentersInfo.getRentersInfoImg());
        //删除旧地址
        ossUtil.deleteFile(path);
        //修改头像
        rentersInfo.setRentersInfoImg(newPath);
        rentersInfoMapper.updateById(rentersInfo);
    }

    /***
     * 完善信息成功
     *
     * @param
     * @param form
     * @param rentersId
     * @return
     */
    @Override
    public void perfectCertifiedInfo(PerfectCertifiedForm form, Integer rentersId) throws Exception {

        Result certified = certifiedClient.findCertifiedInfoById(form.getCertifiedInfoId());
        if (certified.getCode()!=200) {
            throw new Exception("服务繁忙");
        }
        CertifiedDto dtos =(CertifiedDto)certified.getData();
        System.out.println(dtos);
        if (dtos==null) {
            throw new RentersException(RentersExceptionCode.RENTERS_CERTIFIED_ISNO);
        }
        if (!form.getCertifiedInfoName().equals(dtos.getCertifiedInfoName())) {
            throw new RentersException(RentersExceptionCode.RENTERS_CERTIFIED_NAME);
        }
        QueryWrapper<RentersInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("renters_id",rentersId);
        RentersInfo rentersInfo = rentersInfoMapper.selectOne(wrapper);
        rentersInfo.setCertifiedInfoId(form.getCertifiedInfoId());
        rentersInfo.setCertifiedInfoName(form.getCertifiedInfoName());
        rentersInfoMapper.updateById(rentersInfo);

    }
}
